﻿
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Simple.Common.Authentication;
using Simple.Repository.Models.Market;
using Simple.Services.System;
using Simple.Services.System.FileInfo;
using Simple.Services.System.FileInfo.Models;
using Simple.Services.System.Office;
using Simple.Services.System.Office.Model;

namespace Simple.Services
{
    public class ChildrenService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;
        private readonly ExcelOperationService _excelOperationService;
        private readonly FileInfoService _fileInfoService;


        public ChildrenService(SimpleDbContext context,
            ISimpleService services,
            ExcelOperationService excelOperationService,
            FileInfoService fileInfoService) : base(services)
        {
            _context = context;
            _excelOperationService = excelOperationService;
            _fileInfoService = fileInfoService;
        }

        public async Task<List<ChildrenModel>> GetAsync()
        {
            var lstChildrens = await (await OrganizationFilter(_context.Set<Childrens>())).ToListAsync();
            return MapperHelper.Map<List<ChildrenModel>>(lstChildrens);
        }

        public async Task<PageResultModel<ChildrenModel>> GetPageAsync(ChildrenPageInputModel input)
        {
            var result = new PageResultModel<ChildrenModel>();
            var query = await OrganizationFilter(_context.Set<Childrens>().AsQueryable());

            // 根据条件查询
            if (!string.IsNullOrEmpty(input.ChildName))
            {
                query = query.Where(u => u.Name.Contains(input.ChildName));
            }
            if (!string.IsNullOrEmpty(input.ClassId))
            {
                query = query.Where(u => u.ClassesId == input.ClassId);
            }
            if (input.State.HasValue)
            {
                query = query.Where(u => u.ChildState == input.State);
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderBy(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstChild = await query.ToListAsync();
            var lstChildDto = MapperHelper.Map<List<ChildrenModel>>(lstChild);
            if (lstChildDto != null)
            {
                var lstClass = await _context.Set<SysClasses>().ToListAsync();
                var lstChildParent = await _context.Set<ChildrenParent>().Include(p => p.Parent).Select(p => new ChildParentDto()
                {
                    ChildId = p.ChildId,
                    ParentId = p.ParentId,
                    Name = p.Parent.Name,
                    PhoneNumber = p.Parent.PhoneNumber,
                    Relationship = p.Relationship,
                    Workplace = p.Parent.Workplace,
                    Degree = p.Parent.Degree.HasValue ? p.Parent.Degree.Value : EnumParentDegree.Unknown,
                    IsOpenWechat = p.Parent.IsOpenWechat
                }).ToListAsync();
                foreach (var child in lstChildDto)
                {
                    if (!string.IsNullOrEmpty(child.ClassesId))
                    {
                        var classes = lstClass.FirstOrDefault(p => p.Id.ToString() == child.ClassesId);
                        if (classes != null)
                        {
                            child.ClassName = classes.Name;
                        }
                    }
                    child.ParentList = lstChildParent.Where(p => p.ChildId == child.Id).ToList();
                }
            }

            result.Rows = lstChildDto;

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        public async Task<int> AddAsync(ChildrenInputModel model)
        {
            if (await _context.Set<Childrens>().AnyAsync(u => u.StudentNumber == model.StudentNumber) && !string.IsNullOrEmpty(model.StudentNumber))
            {
                throw AppResultException.Status409Conflict("存在相同学号的幼儿");
            }

            var childrens = MapperHelper.Map<Childrens>(model);
            if (!string.IsNullOrEmpty(childrens.ClassesId) && childrens.ChildState != EnumChildState.Grad)
            {
                childrens.ChildState = EnumChildState.Reading;
                childrens.ReadingDay = DateTime.Now;

            }
            childrens.RegisteredDay = DateTime.Now;
            var entityChild = await _context.AddAsync(childrens);

            //保存家长关系
            var lstChildParent = new List<ChildrenParent>();
            foreach (var item in model.childParentInputList)
            {
                lstChildParent.Add(new ChildrenParent()
                {
                    ChildId = entityChild.Entity.Id,
                    ParentId = item.ParentId,
                    Relationship = item.Relationship
                });
            }
            await _context.AddRangeAsync(lstChildParent);

            return await _context.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(ChildrenInputModel model)
        {
            if (await _context.Set<Childrens>().AnyAsync(u => u.Id != model.Id && u.StudentNumber == model.StudentNumber) && !string.IsNullOrEmpty(model.StudentNumber))
            {
                throw AppResultException.Status409Conflict("存在相同学号的幼儿");
            }

            var child = await _context.Set<Childrens>()
                .Where(u => model.Id == u.Id)
                .FirstOrDefaultAsync();

            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            if (model.ClassesId != child.ClassesId)
            {
                child.ReadingDay = DateTime.Now;
            }
            MapperHelper.Map(model, child);

            // 幼儿状态
            if (!string.IsNullOrEmpty(child.ClassesId) && child.ChildState != EnumChildState.Grad)
            {
                child.ChildState = EnumChildState.Reading;
            }
            if (string.IsNullOrEmpty(child.ClassesId))
            {
                child.ChildState = EnumChildState.NotInClass;
            }

            var entityChild = _context.Update(child);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        public async Task<int> DeleteAsync(IEnumerable<Guid> ids)
        {
            var lstChild = await _context.Set<Childrens>()
                .Where(u => ids.Contains(u.Id))
                .ToListAsync();

            _context.RemoveRange(lstChild);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 转班
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> ShiftTransfers(ShiftTransfersDto input)
        {
            var child = await _context.Set<Childrens>()
                .FirstOrDefaultAsync(p => p.Id.ToString() == input.ChildId);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            var classes = await _context.Set<SysClasses>()
                .FirstOrDefaultAsync(p => p.Id.ToString() == input.ClassesId && p.IsArchived == false);
            if (classes == null)
            {
                throw AppResultException.Status404NotFound("找不到班级或班级已归档，更新失败");
            }
            child.ChildState = EnumChildState.Reading;
            child.ClassesId = input.ClassesId;
            child.ReadingDay = DateTime.Now;
            _context.Update(child);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 离班
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> LeaveClass(IdInputModel model)
        {
            var child = await _context.Set<Childrens>()
               .FirstOrDefaultAsync(p => p.Id == model.Id);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            child.ChildState = EnumChildState.NotInClass;
            child.ClassesId = null;
            _context.Update(child);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除关系
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> DeleteRelation(DeleteRelationInput input)
        {
            var relation = await _context.Set<ChildrenParent>()
               .FirstOrDefaultAsync(p => p.ChildId == input.ChildId && p.ParentId == input.ParentId);
            if (relation == null)
            {
                throw AppResultException.Status404NotFound("找不到家属关系，更新失败");
            }
            _context.Remove(relation);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 幼儿导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<FileDownInputModel> ExportChildren(ChildrenPageInputModel input)
        {
            var query = await OrganizationFilter(_context.Set<Childrens>().AsQueryable());

            // 根据条件查询
            if (!string.IsNullOrEmpty(input.ChildName))
            {
                query = query.Where(u => u.Name.Contains(input.ChildName));
            }
            if (!string.IsNullOrEmpty(input.ClassId))
            {
                query = query.Where(u => u.ClassesId == input.ClassId);
            }
            if (input.State.HasValue)
            {
                query = query.Where(u => u.ChildState == input.State);
            }
            var lstChildren = await query.ToListAsync();
            var exportChildren = MapperHelper.Map<List<ExportChildrenModel>>(lstChildren);
            var lstClass = await _context.Set<SysClasses>().ToListAsync();
            foreach (var item in exportChildren)
            {
                if (!string.IsNullOrEmpty(item.ClassesId))
                {
                    var classes = lstClass.FirstOrDefault(p => p.Id.ToString() == item.ClassesId);
                    if (classes != null)
                    {
                        item.ClassName = classes.Name;
                    }
                }
            }


            return await _excelOperationService.ExportAsync(exportChildren, ExportType.Children);
        }

        /// <summary>
        /// 幼儿导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<bool> ImportChildren(List<ChildrenImportInput> importData)
        {
            if (importData != null && importData.Any())
            {
                var lstClassName = importData.Select(p => p.ClassesName).Distinct().ToList();
                var lstClass = await (await OrganizationFilter(_context.Set<SysClasses>())).Where(p => lstClassName.Contains(p.Name)).ToListAsync();
                Dictionary<string, EnumParentRelationship>? lstDicRelation = new Dictionary<string, EnumParentRelationship>();
                foreach (var item in Enum.GetValues(typeof(EnumParentRelationship)))
                {
                    lstDicRelation.Add(EnumHelper.GetDescriptionContent((EnumParentRelationship)item), (EnumParentRelationship)item);
                }
                foreach (var item in importData)
                {
                    item.ChildId = Guid.NewGuid();
                    item.ParentImportList = new List<ParentImportDto>();
                    if (!item.Birthday.HasValue)
                    {
                        throw AppResultException.Status500InternalServerError($"出生日期不能为空");
                    }
                    if (string.IsNullOrWhiteSpace(item.Name))
                    {
                        throw AppResultException.Status500InternalServerError($"幼儿姓名不能为空");
                    }
                    if (string.IsNullOrWhiteSpace(item.Gender))
                    {
                        throw AppResultException.Status500InternalServerError($"性别不能为空");
                    }
                    if (string.IsNullOrWhiteSpace(item.ClassesName))
                    {
                        throw AppResultException.Status500InternalServerError($"班级不能为空");
                    }
                    var classes = lstClass.FirstOrDefault(p => p.Name == item.ClassesName);
                    if (classes == null)
                    {
                        throw AppResultException.Status500InternalServerError($"没有在系统中找到班级【{item.ClassesName}】");
                    }
                    item.ClassId = classes.Id.ToString();
                    if (!string.IsNullOrEmpty(item.RelationshipA) && !string.IsNullOrEmpty(item.ParentNameA) && !string.IsNullOrEmpty(item.ParentPhoneA))
                    {
                        var relation = lstDicRelation.FirstOrDefault(p => p.Key == item.RelationshipA);
                        if (relation.Value == null)
                        {
                            throw AppResultException.Status500InternalServerError($"系统没有维护关系【{item.RelationshipA}】");
                        }
                        item.ParentImportList.Add(new ParentImportDto
                        {
                            ChildId = item.ChildId,
                            Relationship = relation.Value,
                            ParentName = item.ParentNameA,
                            ParentPhone = item.ParentPhoneA,
                        });
                    }
                    if (!string.IsNullOrEmpty(item.RelationshipB) && !string.IsNullOrEmpty(item.ParentNameB) && !string.IsNullOrEmpty(item.ParentPhoneB))
                    {
                        var relation = lstDicRelation.FirstOrDefault(p => p.Key == item.RelationshipB);
                        if (relation.Value == null)
                        {
                            throw AppResultException.Status500InternalServerError($"系统没有维护关系【{item.RelationshipB}】");
                        }
                        item.ParentImportList.Add(new ParentImportDto
                        {
                            ChildId = item.ChildId,
                            Relationship = relation.Value,
                            ParentName = item.ParentNameB,
                            ParentPhone = item.ParentPhoneB,
                        });
                    }
                    if (!string.IsNullOrEmpty(item.RelationshipC) && !string.IsNullOrEmpty(item.ParentNameC) && !string.IsNullOrEmpty(item.ParentPhoneC))
                    {
                        var relation = lstDicRelation.FirstOrDefault(p => p.Key == item.RelationshipC);
                        if (relation.Value == null)
                        {
                            throw AppResultException.Status500InternalServerError($"系统没有维护关系【{item.RelationshipC}】");
                        }
                        item.ParentImportList.Add(new ParentImportDto
                        {
                            ChildId = item.ChildId,
                            Relationship = relation.Value,
                            ParentName = item.ParentNameC,
                            ParentPhone = item.ParentPhoneC,
                        });
                    }
                    if (!string.IsNullOrEmpty(item.RelationshipD) && !string.IsNullOrEmpty(item.ParentNameD) && !string.IsNullOrEmpty(item.ParentPhoneD))
                    {
                        var relation = lstDicRelation.FirstOrDefault(p => p.Key == item.RelationshipD);
                        if (relation.Value == null)
                        {
                            throw AppResultException.Status500InternalServerError($"系统没有维护关系【{item.RelationshipD}】");
                        }
                        item.ParentImportList.Add(new ParentImportDto
                        {
                            ChildId = item.ChildId,
                            Relationship = relation.Value,
                            ParentName = item.ParentNameD,
                            ParentPhone = item.ParentPhoneD,
                        });
                    }
                }
                var lstChild = importData.Select(p => new Childrens
                {
                    Id = p.ChildId.Value,
                    Name = p.Name,
                    StudentNumber = p.StudentNumber,
                    Birthday = p.Birthday,
                    Gender = p.Gender == "男" ? GenderType.Male : GenderType.Female,
                    ClassesId = p.ClassId,
                    ReadingDay = DateTime.Now,
                    ChildState = EnumChildState.Reading,
                    RegisteredDay = DateTime.Now,
                }).ToList();
                await _context.AddRangeAsync(lstChild);
                await _context.SaveChangesAsync();

                var lstNewParent = new List<Parent>();
                var lstNewRelation = new List<ChildrenParent>();
                var lstParent = importData.SelectMany(p => p.ParentImportList).ToList();
                var lsrParentPhone = lstParent.Select(p => p.ParentPhone).ToList();
                var lstExitsParent = await (await OrganizationFilter(_context.Set<Parent>().Where(p => lsrParentPhone.Contains(p.PhoneNumber)))).ToListAsync();
                foreach (var item in lstParent)
                {
                    Guid parentId = Guid.NewGuid();
                    var parent = lstExitsParent.FirstOrDefault(p => p.PhoneNumber == item.ParentPhone);
                    if (parent != null)
                    {
                        parentId = parent.Id;
                    }
                    else
                    {
                        var parentNew = new Parent
                        {
                            Id = parentId,
                            Name = item.ParentName,
                            PhoneNumber = item.ParentPhone,
                            Degree = EnumParentDegree.Unknown,
                            PassWordMD5 = HashHelper.Md5("123456")
                        };
                        if (_currentUser.OrganizationId.ToString() == "08dbdd12-9411-409f-8a68-4f2460cbace6")
                        {
                            parentNew.IsOpenWechat = true;
                        }
                        lstNewParent.Add(parentNew);
                        lstExitsParent.Add(parentNew);
                    }
                    lstNewRelation.Add(new ChildrenParent
                    {
                        ChildId = item.ChildId.Value,
                        ParentId = parentId,
                        Relationship = item.Relationship,
                    });
                }



                await _context.AddRangeAsync(lstNewParent);
                await _context.SaveChangesAsync();
                await _context.AddRangeAsync(lstNewRelation);
                await _context.SaveChangesAsync();
            }

            return true;
        }

        #region 手机端
        /// <summary>
        /// 手机端分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResultModel<ChildrenModel>> GetPageMobileAsync(ChildrenPageInputMobileModel input)
        {
            var result = new PageResultModel<ChildrenModel>();
            var query = await OrganizationFilter(_context.Set<Childrens>().AsQueryable());

            // 根据条件查询
            if (!string.IsNullOrEmpty(input.ChildName))
            {
                query = query.Where(u => u.Name.Contains(input.ChildName));
            }
            if (!string.IsNullOrEmpty(input.ClassId))
            {
                query = query.Where(u => u.ClassesId == input.ClassId);
            }

            // 获取总数量
            result.TotalRows = await query.CountAsync();

            // 分页查询
            query = query.OrderBy(u => u.CreatedTime).Page(input.PageNo, input.PageSize);
            var lstChild = await query.ToListAsync();
            var lstChildDto = MapperHelper.Map<List<ChildrenModel>>(lstChild);
            if (lstChildDto != null)
            {
                var lstClass = await _context.Set<SysClasses>().ToListAsync();
                var lstChildParent = await _context.Set<ChildrenParent>().Include(p => p.Parent).Select(p => new ChildParentDto()
                {
                    ChildId = p.ChildId,
                    ParentId = p.ParentId,
                    Name = p.Parent.Name,
                    PhoneNumber = p.Parent.PhoneNumber,
                    Relationship = p.Relationship,
                    Workplace = p.Parent.Workplace,
                    Degree = p.Parent.Degree.HasValue ? p.Parent.Degree.Value : EnumParentDegree.Elementary,
                    IsOpenWechat = p.Parent.IsOpenWechat
                }).ToListAsync();
                foreach (var child in lstChildDto)
                {
                    if (!string.IsNullOrEmpty(child.ClassesId))
                    {
                        var classes = lstClass.FirstOrDefault(p => p.Id.ToString() == child.ClassesId);
                        if (classes != null)
                        {
                            child.ClassName = classes.Name;
                        }
                    }
                    child.ParentList = lstChildParent.Where(p => p.ChildId == child.Id).ToList();
                }
            }

            result.Rows = lstChildDto;

            result.SetPage(input);
            result.CountTotalPage();

            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> MobileUpdateAsync(ChildrenInputModel model)
        {
            if (await _context.Set<Childrens>().AnyAsync(u => u.Id != model.Id && u.StudentNumber == model.StudentNumber) && !string.IsNullOrEmpty(model.StudentNumber))
            {
                throw AppResultException.Status409Conflict("存在相同学号的幼儿");
            }

            var child = await _context.Set<Childrens>()
                .Where(u => model.Id == u.Id)
                .FirstOrDefaultAsync();

            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            if (model.ClassesId != child.ClassesId)
            {
                child.ReadingDay = DateTime.Now;
            }
            if (!string.IsNullOrEmpty(model.Name))
            {
                child.Name = model.Name;
            }
            if (!string.IsNullOrEmpty(model.StudentNumber))
            {
                child.StudentNumber = model.StudentNumber;
            }
            if (!string.IsNullOrEmpty(model.HomeAddress))
            {
                child.HomeAddress = model.HomeAddress;
            }
            if (!string.IsNullOrEmpty(model.ClassesId))
            {
                child.ClassesId = model.ClassesId;
            }
            if (model.Birthday.HasValue)
            {
                child.Birthday = model.Birthday;
            }
            if (model.Gender.HasValue)
            {
                child.Gender = model.Gender.Value;
            }

            // 幼儿状态
            if (!string.IsNullOrEmpty(child.ClassesId) && child.ChildState != EnumChildState.Grad)
            {
                child.ChildState = EnumChildState.Reading;
            }
            if (string.IsNullOrEmpty(child.ClassesId))
            {
                child.ChildState = EnumChildState.NotInClass;
            }

            var entityChild = _context.Update(child);
            int ret = await _context.SaveChangesAsync();

            if (ret == 0)
            {
                throw AppResultException.Status200OK("更新记录数为0");
            }

            return ret;
        }

        /// <summary>
        /// 转班
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> MobileShiftTransfers(ShiftTransfersDto input)
        {
            var child = await _context.Set<Childrens>()
                .FirstOrDefaultAsync(p => p.Id.ToString() == input.ChildId);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            var classes = await _context.Set<SysClasses>()
                .FirstOrDefaultAsync(p => p.Id.ToString() == input.ClassesId && p.IsArchived == false);
            if (classes == null)
            {
                throw AppResultException.Status404NotFound("找不到班级或班级已归档，更新失败");
            }
            child.ChildState = EnumChildState.Reading;
            child.ClassesId = input.ClassesId;
            child.ReadingDay = DateTime.Now;
            _context.Update(child);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 离班
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> MobileLeaveClass(IdInputModel model)
        {
            var child = await _context.Set<Childrens>()
               .FirstOrDefaultAsync(p => p.Id == model.Id);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            child.ChildState = EnumChildState.NotInClass;
            child.ClassesId = null;
            _context.Update(child);
            return await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 修改关系
        /// </summary>
        /// <returns></returns>
        public async Task<int> MobileUpdateParentRelation(MobileUpdateParentRelationDto dto)
        {
            var parent = await _context.Set<Parent>()
                .FirstOrDefaultAsync(p => p.Id == dto.ParentId);
            if (parent == null)
            {
                throw AppResultException.Status404NotFound("找不到家属，修改失败");
            }
            if (!string.IsNullOrEmpty(dto.ParentName))
            {
                parent.Name = dto.ParentName;
            }
            if (!string.IsNullOrEmpty(dto.PhoneNumber))
            {
                parent.PhoneNumber = dto.PhoneNumber;
            }
            var relation = await _context.Set<ChildrenParent>()
               .FirstOrDefaultAsync(p => p.ParentId == dto.ParentId && p.ChildId == dto.ChildId);
            if (relation != null && dto.Relationship.HasValue)
            {
                relation.Relationship = dto.Relationship.Value;
            }
            return await _context.SaveChangesAsync();
        }

        public async Task<int> MobileUpdateHeadshot(MobileUpdateHeadshotInput input)
        {
            var child = await _context.Set<Childrens>()
               .FirstOrDefaultAsync(p => p.Id == input.ChildId);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            child.ImgId = input.ImgId;
            return await _context.SaveChangesAsync();
        }

        public async Task<MobileChildInfoDto> MobileChildInfo()
        {
            var childId = _currentUser.FindClaimValue(SimpleClaimTypes.ChildId);
            var child = await _context.Set<Childrens>()
               .FirstOrDefaultAsync(p => p.Id.ToString() == childId);
            if (child == null)
            {
                throw AppResultException.Status404NotFound("找不到幼儿，更新失败");
            }
            var result = MapperHelper.Map<MobileChildInfoDto>(child);
            result.Id = child.Id;
            result.ClassId = child.ClassesId;
            if (string.IsNullOrEmpty(child.ClassesId))
            {
                result.ClassName = "未入班";
            }
            else
            {
                var classes = await _context.Set<SysClasses>().FirstOrDefaultAsync(p => p.Id.ToString() == child.ClassesId);
                if (classes != null)
                {
                    result.ClassName = classes.Name;
                }
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 根据班级Id获取家长信息
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public async Task<List<Parent>> GetParentByClassIdAsync(Guid classId)
        {
            var parents = await _context.Set<ChildrenParent>()
                .Include(c => c.Child)
                .Include(c => c.Parent)
                .Where(c => c.Child.ClassesId == classId.ToString())
                .Select(c => c.Parent).ToListAsync();
            return parents;
        }

        /// <summary>
        /// 根据幼儿ID获取对应班级及老师信息
        /// </summary>
        /// <param name="childId"></param>
        /// <returns></returns>
        public async Task<List<Guid>> GetClassTeacherByChildIdAsync(Guid childId)
        {
            var query = from c in _context.Set<Childrens>()
                        join sc in _context.Set<SysClasses>()
                           on c.ClassesId equals sc.Id.ToString()
                        where c.Id == childId
                        select sc.TeacherIds;
            var teacherId = await query.FirstOrDefaultAsync();
            if (!string.IsNullOrWhiteSpace(teacherId))
            {
                return teacherId.Split(",").Select(s => Guid.Parse(s)).ToList();
            }

            return new List<Guid>();
        }

        public async Task BatchUploadAvatarAsync(ChildrenAvatarDto dto)
        { 
            var query = await OrganizationFilter(_context.Set<Childrens>().AsQueryable());
            var childrenList = query.ToList();

            if (dto.ImageList != null && dto.ImageList.Any())
            {
                foreach (var file in dto.ImageList)
                { 
                    var child = childrenList.FirstOrDefault(x => x.StudentNumber == file.FileName.Split('.')[0]);
                    if (child != null && !child.ImgId.HasValue)
                    {
                        var fileId = await _fileInfoService.UploadAsync(new FileInfoInputModel { BusinessType = FileSource.UserPortrait, File = file });
                        childrenList.First(x => x.StudentNumber == file.FileName.Split('.')[0]).ImgId = fileId;
                    } 
                }
            }
            _context.SaveChanges();
        }

        private string GetFileSize(long size)
        {
            var num = 1024.00;
            if (size < num)
                return size + " B";
            if (size < Math.Pow(num, 2))
                return (size / num).ToString("f2") + " KB";
            if (size < Math.Pow(num, 3))
                return (size / Math.Pow(num, 2)).ToString("f2") + " MB";
            if (size < Math.Pow(num, 4))
                return (size / Math.Pow(num, 3)).ToString("f2") + " GB";
            return (size / Math.Pow(num, 4)).ToString("f2") + " TB";
        }

    }
}
